﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms; 
using NTTDATA.BEENChina.ResultCertification.Client.Entry.Model;
using NTTDATA.BEENChina.ResultCertification.Client.Entry.Logic;
using NTTDATA.BEENChina.ResultCertification.Client.Entry.ServiceEntry; 

namespace NTTDATA.BEENChina.ResultCertification.Client.Entry.UI
{
    public partial class JobList : Form
    {
        private bool IsExit = false;
  
        private JobItem[] _lstJob;
        private const string ImagePath = "Data";
 
 

 
        public JobList()
        {
            InitializeComponent();
        } 

        private void JobList_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + "-" + DAppConfig.ServerName;
            
            VerfityJobDateLoad();


            if (listBoxVerfityDate.Items.Count > 0 )
            {
                listBoxVerfityDate.SelectedIndex = 0;
            }

            if (listBoxCategoryType.Items.Count > 0)
            {
                listBoxCategoryType.SelectedIndex = 0;
            }
            
            this.JobTimer.Start();
        }

        private void VerfityJobDateLoad()
        {
            this.listBoxVerfityDate.Tag = this.listBoxVerfityDate.SelectedIndex;

            List<string> orderDates = new JobListHelper().GetVerfityJobDate();


            if (orderDates != null)
            {
                listBoxVerfityDate.DataSource = orderDates.OrderByDescending(t=>t).ToList();
            }

            setSelectedbyTag(this.listBoxVerfityDate);

            GC.Collect();
        }

         
 

        private void btnQuit_Click(object sender, EventArgs e)
        {
            if (IsExit == false)
            {
                if (MessageBox.Show("サインアウトしますか？", "メッセージ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    IsExit = true;
                    this.JobTimer.Dispose();

                   int effactRow = LoginHelper.GetInstance().LogOut();


                   if (effactRow != 1)
                    {
                        MessageBox.Show("Code 1010: " + " アプリケーションプログラムが異常に退出するので、アカウントがロックされた。" + "\n" + "もしアンロックしたら、システム管理員を連絡してください。", "メッセージ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        IsExit = true;
                        this.JobTimer.Dispose();
                    }


                    this.Close();
                }
                else
                {
                    IsExit = false;
                    
                }
            }
        }

        private void JobList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {                
                this.listBoxCategoryType.Tag = this.listBoxCategoryType.SelectedIndex;
                
                this.lvwJobList.Cursor = Cursors.Hand;
                this.VerfityJobDateLoad();
                this.lvwJobList.Cursor = Cursors.Default;
                JobListLoad();

                
                setSelectedbyTag(this.listBoxCategoryType);

            }
        }

        private void setSelectedbyTag(ListBox listbox)
        {
            if (listbox.Items.Count > 0 && listbox.Tag != null)
            {
                listbox.SelectedIndex = (int)listbox.Tag < listbox.Items.Count ? (int)listbox.Tag : 0;
            }
        }

        private void lvwJobList_DoubleClick(object sender, EventArgs e)
        {
            Entry();
        }
        
 

        private void JobTimer_Tick(object sender, EventArgs e)
        {
            this.lvwJobList.Cursor = Cursors.Hand;
            this.VerfityJobDateLoad();
            this.lvwJobList.Cursor = Cursors.Default;
        }

 

        private void listBoxCategoryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            JobListLoad();
        }

        private void JobListLoad()
        {           
            if(this.listBoxVerfityDate.SelectedValue==null)
            {
                return ;
            }



            this.lvwJobList.Tag = this.lvwJobList.SelectedItems.Count > 0 ? this.lvwJobList.SelectedItems[0].Index : 0;

            string orderDate = this.listBoxVerfityDate.SelectedValue.ToString(); 

            string categotyType = this.listBoxCategoryType.SelectedIndex.ToString(CultureInfo.InvariantCulture);

            List<VerfityJobListItem> jobList = new JobListHelper().GetJobList(orderDate, categotyType);

            this.lvwJobList.Items.Clear();

            if (jobList != null)
                foreach (var jobListItem in jobList)
                {

                    ListViewItem item = new ListViewItem();
                    item.Name = jobListItem.VerfityItemName;
                    item.Text = jobListItem.VerfityItemName;
                    item.Tag = string.Format("{0}€{1}",
                        jobListItem.VerfityItemID,
                        jobListItem.CategoryID);
                    

                    //item.SubItems.Add(jobListItem.VerfityItemName);
                    item.SubItems.Add(jobListItem.CategoryName);
                    item.SubItems.Add(jobListItem.ImageCount);

                    lvwJobList.Items.Add(item);
                    // this.lvwJobList.Items.Add()
                }

            if (jobList != null)
                labelImageCount.Text =  jobList.Sum(t => int.Parse( t.ImageCount)).ToString(CultureInfo.InvariantCulture);

            if (lvwJobList.Items.Count > 0 && lvwJobList.Tag != null)
            {
                int selectedIndex = (int)lvwJobList.Tag < lvwJobList.Items.Count ? (int)lvwJobList.Tag : 0;
                lvwJobList.Items[selectedIndex].Selected = true;
            }
        }



        // 窗体的屏幕坐标 
        Point formPoint;
        // 鼠标光标的屏幕坐标
        Point mousePoint;

        private void title_MouseMove(object sender, MouseEventArgs e)
        {
            if (Control.MouseButtons == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                this.Location = this.formPoint + (Size)mousePos - (Size)this.mousePoint;

                LoginHelper.GetInstance().FormEntryPoint = this.Location;
            }
        }

        private void title_MouseDown(object sender, MouseEventArgs e)
        {
            formPoint = this.Location;
            mousePoint = Control.MousePosition;
        }

        private void lvwJobList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                Entry();
            }
        }

        private void Entry()
        {
            //deliveryentry.ShowDialog();
            //return;
            if (this.lvwJobList.SelectedItems.Count > 0)
            {
                this.Cursor = Cursors.WaitCursor;

                string orderDate = LoginHelper.GetInstance().OrderDate = listBoxVerfityDate.SelectedValue.ToString();

                var tagVerfityItemId = this.lvwJobList.SelectedItems[0].Tag.ToString().Split('€')[0];
                var tagCategoryId = this.lvwJobList.SelectedItems[0].Tag.ToString().Split('€')[1];

                string verfityItemId = LoginHelper.GetInstance().VerfityItemId = tagVerfityItemId;
                string categoryId = LoginHelper.GetInstance().CategoryId = tagCategoryId;

                string userId = LoginHelper.GetInstance().UserID;
                DeliveryEntry deliveryentry = new DeliveryEntry();

                deliveryentry._entryjob = new EntryJob();

                VerfityJobItem verfityJobItem = new JobListHelper().DownLoadJob(userId, verfityItemId, categoryId, orderDate);


                if (verfityJobItem != null)
                {
                    deliveryentry._entryjob.JobItem = verfityJobItem;

                    LoginHelper.GetInstance().VerfityJobId = verfityJobItem.VerfityJobID;

                    deliveryentry.ShowDialog();


                }

                //if (deliveryentry._entryjob.JobItem == null)
                //{
                //    this.Cursor = Cursors.Default;
                //    MessageBox.Show(" ダウンロッドジョブーの接続をタイムアウトしました", "メッセージ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}
                //else
                //{
                //    if (deliveryentry._entryjob.JobItem.ChildImage.Length == 0)
                //    {
                //        this.Cursor = Cursors.Default;
                //        MessageBox.Show( " ジョブを完了しまいました、リスクをリフレッシュしてください。", "メッセージ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    }
                //    else
                //    {
                //      /*  if (Directory.Exists(Application.StartupPath + "\\" + ImagePath) == false)
                //        {
                //            Directory.CreateDirectory(Application.StartupPath + "\\" + ImagePath);
                //        }
                //        if (Directory.Exists(Application.StartupPath + "\\" + ImagePath))
                //        {
                //            string[] strDirs = Directory.GetDirectories(Application.StartupPath + "\\" + ImagePath);
                //            string[] strFiles = Directory.GetFiles(Application.StartupPath + "\\" + ImagePath);
                //            foreach (string strFile in strFiles)
                //            {
                //                File.Delete(strFile);
                //            }
                //        }
                //        if (deliveryentry._entryjob.DowindingImage(ImagePath, "UserID") == true)
                //        {
                //            this.JobTimer.Stop();
                //            this.Cursor = Cursors.Default;
                //            //F.编码_追加FormID项目
                //            //deliveryentry.CaseName = _lstCase[this.lbxCaseList.SelectedIndex].CaseName;

                //            deliveryentry.CategoryID = this.lvwJobList.SelectedItems[0].SubItems[2].Text;
                //            deliveryentry.CategoryName = this.lvwJobList.SelectedItems[0].SubItems[0].Text;
                //            deliveryentry.ImagePath = ImagePath;
                //            deliveryentry.UserID = "UserID";
                //            deliveryentry.Timeout = Convert.ToInt16(this.lvwJobList.SelectedItems[0].SubItems[3].Text);
                //            this.Hide();
                //            int x = ((Screen.PrimaryScreen.WorkingArea.Size.Width / 2) - (Screen.PrimaryScreen.WorkingArea.Size.Width - this.Size.Width)) - 35;
                //            int y = ((Screen.PrimaryScreen.WorkingArea.Size.Height / 2) - (Screen.PrimaryScreen.WorkingArea.Size.Height - this.Size.Height)) + 80;
                //            deliveryentry.SetDesktopLocation(x, y);
                //            deliveryentry.ShowDialog();
                //            if (deliveryentry.DialogResult == DialogResult.OK)
                //            {
                //                this.Show();
                //                this.JobTimer.Start();
                //                this.lvwJobList.Cursor = Cursors.Hand;
                //                this.VerfityJobDateLoad();
                //                this.lvwJobList.Cursor = Cursors.Default;
                //            }
                //        }*/
                //    }
                //}

                JobListLoad();

                this.Cursor = Cursors.Default;
                deliveryentry.Dispose();
                GC.Collect();
            }
        }

    }
}
